package com.alibaba.org.controller;

import com.alibaba.basic.annotation.PreAuthorize;
import com.alibaba.org.service.IDepartmentService;
import com.alibaba.org.domain.Department;
import com.alibaba.org.query.DepartmentQuery;
import com.alibaba.basic.util.AjaxResult;
import com.alibaba.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
* 后端接口类；
*/
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Resource
    public IDepartmentService departmentService;

    /**
     * 接口：添加或修改
     * @param department  传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if( department.getId()!=null)
                departmentService.update(department);
            else
                departmentService.add(department);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    /**
    * 接口：删除
    * @param id
    * @return AjaxResult 响应给前端
    */
    @DeleteMapping(value="/{id}")
    @PreAuthorize(name="删除部门" , sn="department:delete")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
        e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return AjaxResult 响应给前端
    */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody Long[] ids){
        try {
                departmentService.patchDelete(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"批量删除失败");
        }
    }

    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}")
    public Department findOne(@PathVariable("id")Long id) {
        return departmentService.findById(id);
    }


    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    public List<Department> findAll(){
        return departmentService.findAll();
    }


   /**
    * 接口：分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query) {
        return departmentService.queryPage(query);
    }

    @GetMapping("/deptTree")
    @PreAuthorize(name="部门树" , sn="department:deptTree")
    public List<Department> deptTree(){
        return departmentService.getDeptTree();
    }

}
